<template>
  <div class="login-container">
    <div class="login-body">
      <div class="login-sidebox"></div>
      <div class="login-form-container">
        <div class="login-head">
          <a-row>
            <a-col :span="6">
              <a-typography-title :level="2">注册</a-typography-title>
            </a-col>
            <a-col :span="9" :push="9">
              <div style="position: absolute; bottom: 16px; right: 0">
                <a-typography-text style="float: left"
                  >已有账号？</a-typography-text
                >
                <a-typography-link @click="login" style="float: right"
                  >点此登录</a-typography-link
                >
              </div>
            </a-col>
          </a-row>
        </div>

        <div>
          <a-space direction="vertical" size="middle">
            <a-form ref="signUpRef" :model="newUser" :rules="rules">
              <a-form-item style="clear: both" name="u_name">
                <a-input
                  class="inputBox"
                  v-model:value="newUser.u_name"
                  placeholder="用户名"
                >
                </a-input>
              </a-form-item>

              <a-form-item name="u_email">
                <a-input
                  class="inputBox"
                  v-model:value="newUser.u_email"
                  placeholder="邮箱地址"
                >
                </a-input>
              </a-form-item>

              <a-form-item name="checkCode">
                <a-input
                  class="checkCodeBox"
                  v-model:value="newUser.checkCode"
                  placeholder="邮箱验证码"
                  :disabled="inputDisabled"
                >
                </a-input>
                <div style="position: absolute; bottom: -12px; left: 182px">
                  <a-button
                    class="getCode"
                    type="primary"
                    ghost
                    block
                    @click="getCheckCode"
                  >
                    获取验证码
                  </a-button>
                </div>
              </a-form-item>

              <a-form-item name="u_pwd">
                <a-input
                  class="inputBox"
                  v-model:value="newUser.u_pwd"
                  placeholder="密码不少于6位"
                >
                </a-input>
              </a-form-item>

              <a-form-item name="u_pwd2">
                <a-input
                  class="inputBox"
                  v-model:value="newUser.u_pwd2"
                  placeholder="确认密码"
                >
                </a-input>
              </a-form-item>
            </a-form>
            <a-button class="submit" type="primary" @click="signUp">
              立即注册
            </a-button>
          </a-space>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { post, tip } from "@/common";
import md5 from "md5";

import { useRouter } from "vue-router";

const router = useRouter(); //获取路由器
const signUpRef = ref();

//reactivr 双向绑定式数据
const newUser = reactive({
  u_name: "",
  u_email: "",
  checkCode: "",
  u_pwd: "",
  u_pwd2: "",
});

const inputDisabled = ref(true);

const validateEmail = async (emailRule, value) => {
  let eReg = /[_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+$/;
  if (value === "") {
    return Promise.reject("邮箱不能为空！");
  } else if (!eReg.test(value)) {
    return Promise.reject("请输入正确的邮箱格式!");
  } else {
    return Promise.resolve();
  }
};

const validateCheckCode = async (checkCodeRule, value) => {
  let cReg = /^[1-9][0-9]{5}\b/;
  if (value === "") {
    return Promise.reject("验证码不能为空！");
  } else if (!cReg.test(value)) {
    return Promise.reject("请输入正确的验证码格式！");
  } else {
    return Promise.resolve();
  }
};

const validatePwd2 = async (rule, value) => {
  if (value === "") {
    return Promise.reject("请输入确认密码！");
  } else if (value !== newUser.u_pwd) {
    return Promise.reject("两次输入密码不一致!");
  } else {
    return Promise.resolve();
  }
};

const rules = {
  u_name: [
    {
      required: true,
      message: "请输入用户名！",
      trigger: "blur",
    },
  ],
  u_email: [
    {
      required: true,
      validator: validateEmail,
      trigger: "blur",
    },
  ],
  checkCode: [
    {
      required: true,
      validator: validateCheckCode,
      trigger: "blur",
    },
  ],
  u_pwd: [
    {
      required: true,
      message: "请输入密码！",
      trigger: "blur",
    },
  ],
  u_pwd2: [
    {
      required: true,
      validator: validatePwd2,
      trigger: "blur",
    },
  ],
};

const getCheckCode = () => {
  signUpRef.value
    .validate(["u_email"])
    .then(() => {
      post(
        "/normal/mail/getcheckcode",
        { email: newUser.email, type: "注册" },
        {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
          },
        }
      ).then((res) => {
        sessionStorage.setItem("email", newUser.u_email);
        sessionStorage.setItem("checkCode", md5(res.data));
        tip.success("验证码发送成功，请及时查看您的邮箱！");
        inputDisabled.value = false;
      });
    })
    .catch((error) => {
      tip.error("输入信息缺失或不正确！");
    });
};

const signUp = () => {
  //then仅接收成功的操作结果
  signUpRef.value
    .validate()
    .then(() => {
      if (md5(newUser.checkCode) != sessionStorage.getItem("checkCode")) {
        tip.error("验证码错误！");
        return;
      }
      newUser.u_email = sessionStorage.getItem("email");
      post("/normal/login/signup", newUser).then((res) => {
        tip.success("注册成功！");

        //跳转至login路由
        router.push({ path: "/login" });
      });
    })
    .catch((error) => {
      tip.error("输入信息缺失或不正确！");
    });
};

const login = () => {
  router.push({ path: "/login" });
};
</script>

<style>
.login-body {
  display: flex;
  width: 1010px;
  height: 522px;
  margin: 65px auto;
  box-shadow: rgb(0, 0, 0, 0.1) 0px 15px 30px;
}

.login-sidebox {
  float: left;
  width: 505px;
  height: 522px;
  padding: 40px 110px;
  background-color: rgb(48, 230, 145);
}

.login-form-container {
  position: relative;
  float: right;
  padding: 40px 70px;
  width: 505px;
  height: 522px;
  background-color: bisque;
}

.login-container {
  position: fixed;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
  display: flex;
}

/* 输入框 */
.inputBox {
  width: 365px;
  height: 36px;
}

.checkCodeBox {
  width: 183px;
  height: 36px;
}

.submit {
  width: 365px;
  height: 36px;
}

.getCode {
  width: 182px;
  height: 37px;
}
</style>